﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace SHCP
{
    /// <summary>
    /// 验证码客户端
    /// </summary>
    public class YZM : WindowBase
    {
        private static int SEQ_NUM = 1;

        public YZM(string name) : base(name) { }

        //确认
        public void Confirm()
        {

            Click(App.Default.YZMConfirmX, App.Default.YZMConfirmY);
        }

        //取消
        public void Esc()
        {
            Click(App.Default.YZMEscX, App.Default.YZMEscY);
        }

        #region 验证码识别
        private static string CuurentImgPath = "";
        private static string CuurentTxtPath = "";
        public bool TryGetValidateCode(out string validateCode)
        {
            validateCode = string.Empty;

            CuurentImgPath = Consts.DataFloderVCode + SEQ_NUM + ".jpg";
            CuurentTxtPath = Consts.DataFloderVCode + SEQ_NUM + ".txt";

            #region 保存图片
            Bitmap btm = new Bitmap(App.Default.YZMVCodeWidth, App.Default.YZMVCodeHeight);
            using (Graphics g = Graphics.FromImage(btm))
            {
                g.CopyFromScreen(Rect.Left + 287, Rect.Top + 107, 0, 0, Screen.AllScreens[0].Bounds.Size);
                btm.Save(CuurentImgPath);
            }
            #endregion

            #region 调用CMD
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe ";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;

            p.Start();
            p.StandardInput.WriteLine(@"cd C:\Program Files\Tesseract-OCR");
            string cmd = "tesseract.exe " + CuurentImgPath + "  " + Consts.DataFloderVCode + SEQ_NUM + " -l eng";//主要这句代码在起作用
            Console.WriteLine(cmd);
            p.StandardInput.WriteLine(cmd);
            p.Close();
            #endregion

            SEQ_NUM++;

            while (!File.Exists(CuurentTxtPath))
            {
                System.Threading.Thread.Sleep(200);
            }

            using (var sr = new StreamReader(CuurentTxtPath))
            {
                validateCode = sr.ReadToEnd().Trim();
                return validateCode.IsCodeRight();
            }
        }
        #endregion
    }
}
